﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using Izhgtu.SandcastlePackage;
using Microsoft.Build.BuildEngine;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Package;
using Microsoft.VisualStudio.Project;
using Microsoft.VisualStudio.Project.Automation;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System.Xml;
using System.Xml.Linq;

namespace Izhgtu.SandcastlePackage
{
    public partial class ContentWindowControl : UserControl
    {
        /// <summary>
        /// Путь к файлу c расширеним .content
        /// </summary>
        private string pathtoLayotFile;


        /// <summary>
        /// Для хранения xml
        /// </summary>
        private XDocument doc;

        /// <summary>
        /// Для хранения Node с default значением
        /// </summary>
        private TreeNode defaultNode;

        /// <summary>
        /// Значение id default topic
        /// </summary>
        string idDefaultTopic;


        public XDocument niktest;

        public ContentWindowControl()
        {
            InitializeComponent();
            this.treeView1.DragDrop += new DragEventHandler(treeView1_DragDrop);
            this.treeView1.ItemDrag += new ItemDragEventHandler(treeView1_ItemDrag);
            this.treeView1.DragOver += new DragEventHandler(treeView1_DragOver);
        }

      private TreeNode GetHoveringNode(int screen_x, int screen_y) {
            Point pt = treeView1.PointToClient(new Point(screen_x, screen_y));
            TreeViewHitTestInfo hitInfo = treeView1.HitTest(pt);
            return hitInfo.Node;
        }

 

        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e) {
            treeView1.DoDragDrop(e.Item, DragDropEffects.All);
        }

 

        private void treeView1_DragOver(object sender, DragEventArgs e) {
            TreeNode hoveringNode = GetHoveringNode(e.X, e.Y);
            TreeNode draggingNode = e.Data.GetData(typeof(TreeNode)) as TreeNode;
           if (hoveringNode != null && hoveringNode != draggingNode) {
                e.Effect = DragDropEffects.Move;
                hoveringNode.TreeView.SelectedNode = hoveringNode;
            } else {
                e.Effect = DragDropEffects.None;
            }

        }

 

        private void treeView1_DragDrop(object sender, DragEventArgs e) {
            if (e.Effect == DragDropEffects.Move) {
                TreeNode hoveringNode = GetHoveringNode(e.X, e.Y);
                if (hoveringNode != null) {
                    TreeNode draggingNode = e.Data.GetData(typeof(TreeNode)) as TreeNode;
                    if (draggingNode != null) {
                        draggingNode.Remove();
                        hoveringNode.Nodes.Add(draggingNode);
                    }
                }                   

            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Получаем текущий проект
            EnvDTE.DTE dte = (EnvDTE.DTE)Package.GetGlobalService(typeof(EnvDTE.DTE));
            EnvDTE.Project project = dte.Solution.Projects.Item(1);

            //В Проекте ищем файл c расширением .content          
            foreach (ProjectItem var in project.ProjectItems)
            {
                string name = var.Name;               

                if (name.EndsWith(".content"))
                {

                    SandcastleFileNode node = (SandcastleFileNode)((OAVSProjectItem)var.Object).FileNode;

                    pathtoLayotFile = node.Url;
                    // Загружаем XML
                    LoadXMl();
                }
            }
        }


        // Здесь можешь написать какую-нибудь проверку...
        private void PrintRecursive(TreeNode treeNode, XElement bnode)
        {
            Izhgtu.SandcastlePackage.Items.Topic topic = (Izhgtu.SandcastlePackage.Items.Topic)treeNode.Tag;

            XElement element = new XElement("Topic",
                                    new XAttribute("id", topic.guid),
                                    new XAttribute("visible", topic.visible),
                                    new XAttribute("title", topic.title));


            if (treeNode.Parent == null)
            {
                niktest.Root.Add(element);
            }
            else
            {
                bnode.Add(element);
            }
            
           
            System.Diagnostics.Debug.WriteLine(treeNode.Text);

            foreach (TreeNode tn in treeNode.Nodes)
            {
                PrintRecursive(tn, element);               
            }            

        }


        private void LoadRecurSiveXMLtoTreeView(XElement element, TreeNode _node)
        {
            try
            {
                TreeNode node = new TreeNode(element.Attribute("title").Value.ToString());

                String title = element.Attribute("title").Value;
                Guid guid = new Guid(element.Attribute("id").Value);
                bool visible = Convert.ToBoolean(element.Attribute("visible").Value);

                if (idDefaultTopic.Equals(guid.ToString()))
                {
                    node.ForeColor = Color.Red;
                    defaultNode = node;
                }


                Izhgtu.SandcastlePackage.Items.Topic top = new Izhgtu.SandcastlePackage.Items.Topic(guid, title, visible);

                node.Tag = top;

                if (_node == null)
                {
                    treeView1.Nodes.Add(node);
                }
                else
                {
                    _node.Nodes.Add(node);
                }


                foreach (XElement ele in element.Elements())
                {
                    LoadRecurSiveXMLtoTreeView(ele, node);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Не валидный Content Layout: " + ex.ToString());
            }
        }






        private void LoadXMl()
        {
            //Очищаем 
            treeView1.Nodes.Clear();

            //Если файл существует то загружаем его в обьектуную модель
            if (File.Exists(pathtoLayotFile))
            {
                doc = XDocument.Load(pathtoLayotFile);

                idDefaultTopic = doc.Root.Attribute("defaultTopic").Value;

                foreach (XElement el in doc.Root.Elements())
                {
                    LoadRecurSiveXMLtoTreeView(el, null);
                }
                
            } 
        }


        
        /// <summary>
        /// Поднимаем вверх
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            TreeNode parent = treeView1.SelectedNode.Parent;
            TreeNode selected_node = treeView1.SelectedNode;
            TreeNode prev_node = selected_node.PrevNode;
            if (parent == null)
            {
              //  parent. = treeView1.Nodes;
            }

            if (prev_node != null)
            {
                selected_node.Remove();
                if (parent != null)
                {
                    parent.Nodes.Insert(prev_node.Index, selected_node);
                }
                else
                {
                    treeView1.Nodes.Insert(prev_node.Index, selected_node);
                }
                treeView1.SelectedNode = selected_node;
            }
            else 
            {
                MessageBox.Show("Не может быть выше");
            }

        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }


        /// <summary>
        /// Опускаем в низ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {



            TreeNode parent = treeView1.SelectedNode.Parent;
            TreeNode selected_node = treeView1.SelectedNode;
            TreeNode next_node = selected_node.NextNode;
            if (parent == null)
            {
                //  parent. = treeView1.Nodes;
            }

            if (next_node != null)
            {
                selected_node.Remove();
                if (parent != null)
                {
                    parent.Nodes.Insert(next_node.Index+1, selected_node);
                }
                else
                {
                    treeView1.Nodes.Insert(next_node.Index+1, selected_node);
                }
                treeView1.SelectedNode = selected_node;
            }
            else
            {
                MessageBox.Show("Не может быть ниже");
            }
        }

        private void setDefaultToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = treeView1.SelectedNode;
            Izhgtu.SandcastlePackage.Items.Topic topic = (Izhgtu.SandcastlePackage.Items.Topic)node.Tag;

            //Запоминаем id            
            idDefaultTopic = topic.guid.ToString();

            node.ForeColor = Color.Red;
            defaultNode.ForeColor = Color.Black;
            defaultNode = node;
        }






        private void treeView1_MouseMove(object sender, MouseEventArgs e)
        {
 
        }

        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            TreeNode mySelectedNode = treeView1.GetNodeAt(e.X, e.Y);
            treeView1.SelectedNode = mySelectedNode;

        }


       
        /// <summary>
        /// Сохраняем в файл Content Loyat
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                niktest = new XDocument(new XElement("Topics", new XAttribute("defaultTopic", idDefaultTopic)));

                foreach (TreeNode nod in treeView1.Nodes)
                {
                    PrintRecursive(nod, null);

                }
                niktest.Save(pathtoLayotFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка сохранения : " + ex.Message);
            }
            
        }

     

    }
}
